/****************************************************************************
**
** Copyright (C) 2015 The Qt Company Ltd.
** Contact: http://www.qt.io/licensing/
**
** This file is part of the examples of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:BSD$
** You may use this file under the terms of the BSD license as follows:
**
** "Redistribution and use in source and binary forms, with or without
** modification, are permitted provided that the following conditions are
** met:
**   * Redistributions of source code must retain the above copyright
**     notice, this list of conditions and the following disclaimer.
**   * Redistributions in binary form must reproduce the above copyright
**     notice, this list of conditions and the following disclaimer in
**     the documentation and/or other materials provided with the
**     distribution.
**   * Neither the name of The Qt Company Ltd nor the names of its
**     contributors may be used to endorse or promote products derived
**     from this software without specific prior written permission.
**
**
** THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
** "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
** LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
** A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
** OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
** LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
** DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
** THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
** (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE."
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "player.h"

#include "playercontrols.h"
#include "playlistmodel.h"
//#include "histogramwidget.h"
#include "confdeal.h"

#include <QMediaService>
#include <QMediaPlaylist>
//#include <QVideoProbe>
#include <QListView>
#include <QMediaMetaData>
#include <QtWidgets>
#include <QDebug>
#include <QtGlobal>
#include <QDir>
#include <QFileInfo>

Player::Player(QWidget *parent)
    : QWidget(parent)
    , videoWidget(0)
    , coverLabel(0)
    , slider(0)
    , colorDialog(0)
    , rootrun(true)
    , playrun(true)
{
    ConfDeal *ptr_ConfDeal = ConfDeal::getInstance();
    defMediaDir = ptr_ConfDeal->getMediaDir();
    qInfo()<<QString("defMediaDir=%1").arg(defMediaDir);
//! [create-objs]
    player = new QMediaPlayer(this);
    // owned by PlaylistModel
    playlist = new QMediaPlaylist();
    player->setPlaylist(playlist);
//! [create-objs]

    connect(player, SIGNAL(durationChanged(qint64)), SLOT(durationChanged(qint64)));
    connect(player, SIGNAL(positionChanged(qint64)), SLOT(positionChanged(qint64)));
    connect(player, SIGNAL(metaDataChanged()), SLOT(metaDataChanged()));
    connect(playlist, SIGNAL(currentIndexChanged(int)), SLOT(playlistPositionChanged(int)));
    connect(player, SIGNAL(mediaStatusChanged(QMediaPlayer::MediaStatus)),
            this, SLOT(statusChanged(QMediaPlayer::MediaStatus)));
    connect(player, SIGNAL(bufferStatusChanged(int)), this, SLOT(bufferingProgress(int)));
    connect(player, SIGNAL(videoAvailableChanged(bool)), this, SLOT(videoAvailableChanged(bool)));
    connect(player, SIGNAL(error(QMediaPlayer::Error)), this, SLOT(displayErrorMessage()));

//! [2]
    videoWidget = new VideoWidget(this);
    player->setVideoOutput(videoWidget);

    playlistModel = new PlaylistModel(this);
    playlistModel->setPlaylist(playlist);
//! [2]

    playlistView = new QListView(this);
    playlistView->setModel(playlistModel);
    playlistView->setViewMode(QListView::ListMode);
    playlistView->setResizeMode(QListView::Fixed);
//    playlistView->setWordWrap(true);
    playlistView->setCurrentIndex(playlistModel->index(playlist->currentIndex(), 0));

    connect(playlistView, SIGNAL(activated(QModelIndex)), this, SLOT(jump(QModelIndex)));

    slider = new QSlider(Qt::Horizontal, this);
    slider->setRange(0, player->duration() / 1000);

    labelDuration = new QLabel(this);
    connect(slider, SIGNAL(sliderMoved(int)), this, SLOT(seek(int)));

//    labelHistogram = new QLabel(this);
//    labelHistogram->setText("Histogram:");
//    histogram = new HistogramWidget(this);
//    QHBoxLayout *histogramLayout = new QHBoxLayout;
//    histogramLayout->addWidget(labelHistogram);
//    histogramLayout->addWidget(histogram, 1);

//    probe = new QVideoProbe(this);
//    connect(probe, SIGNAL(videoFrameProbed(QVideoFrame)), histogram, SLOT(processFrame(QVideoFrame)));
//    probe->setSource(player);
    //
    QFont _font("Courier New", 9);
//    _font.setBold(true);
    _font.setWeight(QFont::Light);
    this->setFont(_font);
    //
    QPalette pl = this->palette();
    pl.setColor(QPalette::Base,QColor(240,240,240));
    pl.setColor(QPalette::Window,QColor(235,235,235));
    pl.setColor(QPalette::Text,QColor(4,58,59));
    pl.setColor(QPalette::ButtonText,QColor(4,58,59));
    pl.setColor(QPalette::WindowText,QColor(4,58,59));
    this->setPalette(pl);
    //
    QPushButton *openButton = new QPushButton(tr("Open"), this);
//    openButton->setIcon(style()->standardIcon(QStyle::SP_DirOpenIcon));
//    QString pushButton_SS = "QPushButton{border-radius: 5px; /*圆角半径*/"
//                            "border:1px solid grey;"
//                            "color:blue;/*字体颜色*/"
//                            "background-color: white;/*背景颜色*/"
//                            "}";
//    openButton->setStyleSheet(pushButton_SS);
    connect(openButton, SIGNAL(clicked()), this, SLOT(open()));

    PlayerControls *controls = new PlayerControls(this);
    controls->setState(player->state());
    controls->setVolume(player->volume());
    controls->setMuted(controls->isMuted());

    connect(controls, SIGNAL(play()), player, SLOT(play()));
    connect(controls, SIGNAL(pause()), player, SLOT(pause()));
    connect(controls, SIGNAL(stop()), player, SLOT(stop()));
    connect(controls, SIGNAL(next()), playlist, SLOT(next()));
    connect(controls, SIGNAL(previous()), this, SLOT(previousClicked()));
    connect(controls, SIGNAL(changeVolume(int)), player, SLOT(setVolume(int)));
    connect(controls, SIGNAL(changeMuting(bool)), player, SLOT(setMuted(bool)));
    connect(controls, SIGNAL(changeRate(qreal)), player, SLOT(setPlaybackRate(qreal)));

    connect(controls, SIGNAL(stop()), videoWidget, SLOT(update()));

    connect(player, SIGNAL(stateChanged(QMediaPlayer::State)),
            controls, SLOT(setState(QMediaPlayer::State)));
    connect(player, SIGNAL(volumeChanged(int)), controls, SLOT(setVolume(int)));
    connect(player, SIGNAL(mutedChanged(bool)), controls, SLOT(setMuted(bool)));

    fullScreenButton = new QPushButton(tr("FullScreen"), this);
    fullScreenButton->setCheckable(true);

    colorButton = new QPushButton(tr("Color Options..."), this);
    colorButton->setEnabled(false);
    connect(colorButton, SIGNAL(clicked()), this, SLOT(showColorDialog()));

    QBoxLayout *displayLayout = new QHBoxLayout;
    displayLayout->setContentsMargins(0,0,0,0);
    displayLayout->addWidget(videoWidget,2);
    displayLayout->addWidget(playlistView);

    QBoxLayout *controlLayout = new QHBoxLayout;
    controlLayout->setContentsMargins(0,0,0,0);
    controlLayout->setMargin(0);
    //controlLayout->addStretch(1);
    controlLayout->addWidget(controls);
    //controlLayout->addStretch(1);
    controlLayout->addWidget(openButton);
    controlLayout->addWidget(fullScreenButton);
    controlLayout->addWidget(colorButton);
    controlLayout->addWidget(new QWidget(),7);

    QBoxLayout *layout = new QVBoxLayout;
    layout->setContentsMargins(5,5,5,5);
    layout->addLayout(displayLayout);
    QHBoxLayout *hLayout = new QHBoxLayout;
    hLayout->setContentsMargins(0,0,0,0);
    hLayout->addWidget(slider);
    hLayout->addWidget(labelDuration);
    layout->addLayout(hLayout);
    layout->addLayout(controlLayout);
//    layout->addLayout(histogramLayout);

    setLayout(layout);

    if (!isPlayerAvailable()) {
        QMessageBox::warning(this, tr("Service not available"),
                             tr("The QMediaPlayer object does not have a valid service.\n"\
                                "Please check the media service plugins are installed."));

        controls->setEnabled(false);
        playlistView->setEnabled(false);
        openButton->setEnabled(false);
        colorButton->setEnabled(false);
        fullScreenButton->setEnabled(false);
    }

    metaDataChanged();
    loadDefMedia(defMediaDir);
    int _pleymodel = ptr_ConfDeal->getPlayModel();
    control(101,_pleymodel);
    int _fullScreen = ptr_ConfDeal->getFullScreen();
    control(5,_fullScreen);
    int _autoPlay = ptr_ConfDeal->getAutoPlay();
    control(3,_autoPlay);
    this->setWindowIcon(QIcon(":/images/zhsye.png"));
}

Player::~Player()
{
}

bool Player::isPlayerAvailable() const
{
    return player->isAvailable();
}

void Player::loadDefMedia(QString _dir)
{
    QDir dir(_dir);
//    qInfo()<<dir.absolutePath();
    QStringList _medias = dir.entryList(QDir::Files);
//    qInfo() << "_medias="<<_medias;
    QList<QUrl> _mediaUrls;
    for(int i=0; i<_medias.size(); i++){
        _mediaUrls << QUrl(dir.absolutePath()+"/"+_medias.at(i));
    }
    addToPlaylist(_mediaUrls);
};

void Player::open()
{
    QFileDialog fileDialog(this);
    fileDialog.setPalette(this->palette());
    fileDialog.setAcceptMode(QFileDialog::AcceptOpen);
    fileDialog.setWindowTitle(tr("Open Files"));
    QStringList supportedMimeTypes = player->supportedMimeTypes();
    if (!supportedMimeTypes.isEmpty()) {
        supportedMimeTypes.append("audio/x-m3u"); // MP3 playlists
        fileDialog.setMimeTypeFilters(supportedMimeTypes);
    }
    if(!defMediaDir.isEmpty()){
        fileDialog.setDirectory(defMediaDir);
    }else{
        fileDialog.setDirectory(QStandardPaths::standardLocations(QStandardPaths::MoviesLocation).value(0, QDir::homePath()));
    }
    if (fileDialog.exec() == QDialog::Accepted){
//        for(int i=0; i<fileDialog.selectedUrls().size(); i++){
//            qInfo()<<QString("add the url(%1) to play list\n").arg(fileDialog.selectedUrls().at(i).path());
//        }
        addToPlaylist(fileDialog.selectedUrls());
    }
}

static bool isPlaylist(const QUrl &url) // Check for ".m3u" playlists.
{
    if (!url.isLocalFile())
        return false;
    const QFileInfo fileInfo(url.toLocalFile());
    return fileInfo.exists() && !fileInfo.suffix().compare(QLatin1String("m3u"), Qt::CaseInsensitive);
}

void Player::addToPlaylist(const QList<QUrl> urls)
{
    foreach (const QUrl &url, urls) {
        qInfo()<< QString("add media(%1) to list").arg(url.path());
        if (isPlaylist(url))
            playlist->load(url);
        else
            playlist->addMedia(url);
    }
}

void Player::durationChanged(qint64 duration)
{
    this->duration = duration/1000;
    slider->setMaximum(duration / 1000);
}

void Player::positionChanged(qint64 progress)
{
    curpos = progress/1000;
    if (!slider->isSliderDown()) {
        slider->setValue(progress / 1000);
    }
    updateDurationInfo(progress / 1000);
}

void Player::metaDataChanged()
{
    if (player->isMetaDataAvailable()) {
        setTrackInfo(QString("%1 - %2")
                .arg(player->metaData(QMediaMetaData::AlbumArtist).toString())
                .arg(player->metaData(QMediaMetaData::Title).toString()));

        if (coverLabel) {
            QUrl url = player->metaData(QMediaMetaData::CoverArtUrlLarge).value<QUrl>();

            coverLabel->setPixmap(!url.isEmpty()
                    ? QPixmap(url.toString())
                    : QPixmap());
        }
    }
}

void Player::previousClicked()
{
    // Go to previous track if we are within the first 5 seconds of playback
    // Otherwise, seek to the beginning.
    if(player->position() <= 5000)
        playlist->previous();
    else
        player->setPosition(0);
}

void Player::jump(const QModelIndex &index)
{
    if (index.isValid()) {
        playlist->setCurrentIndex(index.row());
        player->play();
    }
}

void Player::playlistPositionChanged(int currentItem)
{
    playlistView->setCurrentIndex(playlistModel->index(currentItem, 0));
}

void Player::seek(int seconds)
{
    player->setPosition(seconds * 1000);
}

void Player::statusChanged(QMediaPlayer::MediaStatus status)
{
    handleCursor(status);

    // handle status message
    switch (status) {
    case QMediaPlayer::UnknownMediaStatus:
    case QMediaPlayer::NoMedia:
    case QMediaPlayer::LoadedMedia:
    case QMediaPlayer::BufferingMedia:
    case QMediaPlayer::BufferedMedia:
        setStatusInfo(QString());
        break;
    case QMediaPlayer::LoadingMedia:
        setStatusInfo(tr("Loading..."));
        break;
    case QMediaPlayer::StalledMedia:
        setStatusInfo(tr("Media Stalled"));
        break;
    case QMediaPlayer::EndOfMedia:
//        QApplication::alert(this);
        break;
    case QMediaPlayer::InvalidMedia:
        displayErrorMessage();
        break;
    }
    emit notify();
}

void Player::handleCursor(QMediaPlayer::MediaStatus status)
{
#ifndef QT_NO_CURSOR
    if (status == QMediaPlayer::LoadingMedia ||
        status == QMediaPlayer::BufferingMedia ||
        status == QMediaPlayer::StalledMedia)
        setCursor(QCursor(Qt::BusyCursor));
    else
        unsetCursor();
#endif
}

void Player::bufferingProgress(int progress)
{
    setStatusInfo(tr("Buffering %4%").arg(progress));
}

void Player::videoAvailableChanged(bool available)
{
    if (!available) {
        disconnect(fullScreenButton, SIGNAL(clicked(bool)),
                    videoWidget, SLOT(setFullScreen(bool)));
        disconnect(videoWidget, SIGNAL(fullScreenChanged(bool)),
                fullScreenButton, SLOT(setChecked(bool)));
        videoWidget->setFullScreen(false);
    } else {
        connect(fullScreenButton, SIGNAL(clicked(bool)),
                videoWidget, SLOT(setFullScreen(bool)));
        connect(videoWidget, SIGNAL(fullScreenChanged(bool)),
                fullScreenButton, SLOT(setChecked(bool)));

        if (fullScreenButton->isChecked())
            videoWidget->setFullScreen(true);
    }
    colorButton->setEnabled(available);
}

void Player::setTrackInfo(const QString &info)
{
    trackInfo = info;
    if (!statusInfo.isEmpty())
        setWindowTitle(QString("%1 | %2").arg(trackInfo).arg(statusInfo));
    else
        setWindowTitle(trackInfo);
}

void Player::setStatusInfo(const QString &info)
{
    statusInfo = info;
    if (!statusInfo.isEmpty())
        setWindowTitle(QString("%1 | %2").arg(trackInfo).arg(statusInfo));
    else
        setWindowTitle(trackInfo);
}

void Player::displayErrorMessage()
{
    setStatusInfo(player->errorString());
}

void Player::updateDurationInfo(qint64 currentInfo)
{
    QString tStr;
    if (currentInfo || duration) {
        QTime currentTime((currentInfo/3600)%60, (currentInfo/60)%60, currentInfo%60, (currentInfo*1000)%1000);
        QTime totalTime((duration/3600)%60, (duration/60)%60, duration%60, (duration*1000)%1000);
        QString format = "mm:ss";
        if (duration > 3600)
            format = "hh:mm:ss";
        tStr = currentTime.toString(format) + " / " + totalTime.toString(format);
    }
    labelDuration->setText(tStr);
}

void Player::showColorDialog()
{
    if (!colorDialog) {
        QSlider *brightnessSlider = new QSlider(Qt::Horizontal);
        brightnessSlider->setRange(-100, 100);
        brightnessSlider->setValue(videoWidget->brightness());
        connect(brightnessSlider, SIGNAL(sliderMoved(int)), videoWidget, SLOT(setBrightness(int)));
        connect(videoWidget, SIGNAL(brightnessChanged(int)), brightnessSlider, SLOT(setValue(int)));

        QSlider *contrastSlider = new QSlider(Qt::Horizontal);
        contrastSlider->setRange(-100, 100);
        contrastSlider->setValue(videoWidget->contrast());
        connect(contrastSlider, SIGNAL(sliderMoved(int)), videoWidget, SLOT(setContrast(int)));
        connect(videoWidget, SIGNAL(contrastChanged(int)), contrastSlider, SLOT(setValue(int)));

        QSlider *hueSlider = new QSlider(Qt::Horizontal);
        hueSlider->setRange(-100, 100);
        hueSlider->setValue(videoWidget->hue());
        connect(hueSlider, SIGNAL(sliderMoved(int)), videoWidget, SLOT(setHue(int)));
        connect(videoWidget, SIGNAL(hueChanged(int)), hueSlider, SLOT(setValue(int)));

        QSlider *saturationSlider = new QSlider(Qt::Horizontal);
        saturationSlider->setRange(-100, 100);
        saturationSlider->setValue(videoWidget->saturation());
        connect(saturationSlider, SIGNAL(sliderMoved(int)), videoWidget, SLOT(setSaturation(int)));
        connect(videoWidget, SIGNAL(saturationChanged(int)), saturationSlider, SLOT(setValue(int)));

        QFormLayout *layout = new QFormLayout;   
        layout->addRow(tr("Brightness"), brightnessSlider);
        layout->addRow(tr("Contrast"), contrastSlider);
        layout->addRow(tr("Hue"), hueSlider);
        layout->addRow(tr("Saturation"), saturationSlider);

        QPushButton *button = new QPushButton(tr("Close"));
//        button->setFixedWidth(120);
//        button->setIcon(style()->standardIcon(QStyle::SP_DialogCloseButton));
        layout->addRow(button);

        colorDialog = new QDialog(this);
        colorDialog->setPalette(this->palette());
        colorDialog->setWindowTitle(tr("Color Options"));
//        layout->setFormAlignment(Qt::AlignHCenter);
        colorDialog->setLayout(layout);

        connect(button, SIGNAL(clicked()), colorDialog, SLOT(close()));
    }
    colorDialog->show();
}

void Player::control(int id,int val)
{
    qDebug()<<QString("Player::control(%1,%2)").arg(id).arg(val);
    /*
     * YX
    */
    if(id<100){
        bool controlf = val>0?true:false;
        switch(id)
        {
        //2019-06-26,将终端重启 App启停迁移到终端辅助监控服务
//        case 1:
//        {
//            if(controlf){
//                rootrun = true;
//            }else{
//                ConfDeal *ptr_ConfDeal = ConfDeal::getInstance();
//                QString cmdFile = ptr_ConfDeal->getappDir()
//                        +ptr_ConfDeal->getpathDiv()
//            #ifdef WIN32
//                        +"reboot.bat";
//            #else
//                        +"reboot.sh";
//            #endif
//                if(QFileInfo::exists(cmdFile)){
//                    system(cmdFile.toStdString().c_str());
//                    rootrun = false;
//                }
//			}
//            break;
//        }
//        case 2:
//        {
//            if(controlf){
//                rootrun = true;
//            }else{
//                ConfDeal *ptr_ConfDeal = ConfDeal::getInstance();
//                QString cmdFile = ptr_ConfDeal->getappDir()
//                        +ptr_ConfDeal->getpathDiv()
//            #ifdef WIN32
//                        +"replayer.bat";
//            #else
//                        +"replayer.sh";
//            #endif
//                if(QFileInfo::exists(cmdFile)){
//                    system(cmdFile.toStdString().c_str());
//                    playrun = false;
//                }
//			}
//            break;
//        }
        //播放状态
        case 3:
        {
            if(controlf)
                player->play();
            else
                player->stop();
        }
            break;
        //正播放状态
        case 4:
        {
            if(controlf)
                player->play();
            else
                player->pause();
        }
            break;
        //全屏状态
        case 5:
        {
            videoWidget->setFullScreen(controlf);
        }
            break;
        case 6:
        {
        }
            break;
        default:
            break;
        }
    }else if(id>100&&id<200)
    {
        switch(id)
        {
        //播放模式
        case 101:
        {
            switch (val) {
            case 1:
                playlist->setPlaybackMode(QMediaPlaylist::CurrentItemOnce);
                break;
            case 2:
                playlist->setPlaybackMode(QMediaPlaylist::CurrentItemInLoop);
                break;
            case 3:
                playlist->setPlaybackMode(QMediaPlaylist::Sequential);
                break;
            case 4:
                playlist->setPlaybackMode(QMediaPlaylist::Loop);
                break;
            case 5:
                playlist->setPlaybackMode(QMediaPlaylist::Random);
                break;
            default:
                break;
            }
        }
            break;
        //播放索引
        case 103:
        {
            int playCount = playlist->mediaCount();
            if(val<playCount&&val>=0)
                playlist->setCurrentIndex(val);
        }
            break;
        //播放位置
        case 104:
        {
            qreal posRate = qreal(val)/100.0;
            qint64 intRate = duration*1000*posRate;
            qInfo() << QString("play pos is %1").arg(intRate);
            player->setPosition(intRate);
        }
            break;
        //声音
        case 105:
        {
            int _val = val;
            if(val>100){
                _val = 100;
            }
            if(val<0){
                _val = 0;
            }
            player->setVolume(_val);
        }
            break;
        //播放速率
        case 107:
        {
            int _val = val;
            if(val>50){
                _val = 50;
            }
            if(val<2){
                _val = 2;
            }
            player->setPlaybackRate(qreal(_val)/10.0);
        }
            break;
        default:
            break;
        }
    }else{
        ;
    }
    emit notify();
}

void Player::getState(QMap<int,int> &playStates)
{
    playStates.clear();
//    //
//    playStates[1] = rootrun;
//    playStates[2] = playrun;
    //YX
    //播放状态
    QMediaPlayer::State _state = player->state();
    switch(_state)
    {
    case QMediaPlayer::PlayingState:
    {
        playStates[3] = 1;
        playStates[4] = 1;
    }
        break;
    case QMediaPlayer::PausedState:
    {
        playStates[3] = 1;
        playStates[4] = 0;
    }
        break;
    case QMediaPlayer::StoppedState:
    {
        playStates[3] = 0;
        playStates[4] = 0;
    }
        break;
    default:
        break;
    }
    //全屏状况
    bool fullScreenF = videoWidget->isFullScreen();
    if(fullScreenF){
        playStates[5] = 1;
    }else{
        playStates[5] = 0;
    }
    /*
     * YC
    */
    //回放模式
    QMediaPlaylist::PlaybackMode playmodel = playlist->playbackMode();
    switch (playmodel) {
    case QMediaPlaylist::CurrentItemOnce:
        playStates[101] = 1;
        break;
    case QMediaPlaylist::CurrentItemInLoop:
        playStates[101] = 2;
        break;
    case QMediaPlaylist::Sequential:
        playStates[101] = 3;
        break;
    case QMediaPlaylist::Loop:
        playStates[101] = 4;
        break;
    case QMediaPlaylist::Random:
        playStates[101] = 5;
        break;
    default:
        break;
    }
    //列表片源数量
    int playCount = playlist->mediaCount();
    playStates[102] = playCount;
    //当前片源索引
    int playIndex = playlist->currentIndex();
    if(playIndex<0)
        playIndex = 0;
    playStates[103] = playIndex;
    //声音
    int vol = player->volume();
    playStates[105] = vol;

    //媒体状态
    QMediaPlayer::MediaStatus _mstatus = player->mediaStatus();
    switch(_mstatus)
    {
    case QMediaPlayer::UnknownMediaStatus:
        playStates[106] = 1;
        break;
    case QMediaPlayer::NoMedia:
         playStates[106] = 2;
        break;
    case QMediaPlayer::LoadingMedia:
         playStates[106] = 3;
        break;
    case QMediaPlayer::LoadedMedia:
         playStates[106] = 4;
        break;
    case QMediaPlayer::StalledMedia:
         playStates[106] = 5;
        break;
    case QMediaPlayer::BufferingMedia:
         playStates[106] = 6;
        break;
    case QMediaPlayer::BufferedMedia:
         playStates[106] = 7;
        break;
    case QMediaPlayer::EndOfMedia:
         playStates[106] = 8;
         player->setPosition(0);
        break;
    case QMediaPlayer::InvalidMedia:
         playStates[106] = 9;
        break;
    default:
        break;
    }
    //播放位置,2018-04-28代码因player->setPosition(0)；剪切到此
    qreal pos = 100.0*(qreal(curpos)/qreal(duration));
    playStates[104] = int(pos);
    playStates[104] = playStates[104]>100?100:playStates[104];
    //播放速率
    qreal prate =  player->playbackRate();
    if(0.0==prate)
        prate = 1.0;
    playStates[107] = int(prate*10);
}
